package com.mango.acat.core.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.google.common.io.Files;
import com.mango.acat.core.annotation.ReqKey;
import com.mango.acat.core.ioc.IocFactory;
import com.mango.acat.core.setting.AppSetting;
import com.xiaoleilu.hutool.util.ClassUtil;
import com.xiaoleilu.hutool.util.FileUtil;

import freemarker.cache.StringTemplateLoader;

public class InitKit {
	
	private static String baseRoot = AppSetting.app.getStr("app.content.path","");
	
	public static void initCommonFreemarker() throws IOException{
        StringTemplateLoader stringLoader = (StringTemplateLoader) IocFactory.getObject(StringTemplateLoader.class);
        //递归加载html 的 freemarker模板
        loadFreemarkerScanDir(stringLoader, baseRoot);
        System.out.println("acat freemarker模板加载，loading=="+stringLoader.toString());
	}
	
	private static void loadFreemarkerScanDir(StringTemplateLoader stringLoader,String br) throws IOException{
		for(File f : FileUtil.ls(br)){
			String filename = f.getName();
	    	if("html".equals(Files.getFileExtension(filename))){
	    		String filepath = f.getPath();
	    		filepath = filepath.substring(baseRoot.length());
	    		filepath = filepath.replaceAll("\\\\", "/");
	    		filepath = filepath.substring(1);
	    		//是页面文件，就加载到freemarker的模板中
	    		stringLoader.putTemplate(filepath, Files.toString(new File(br+"/"+filename),Charset.forName("utf-8")));
	    	}
	    	if(f.isDirectory()){
	    		loadFreemarkerScanDir(stringLoader, f.getAbsolutePath());
	    	}
        }
	}
	/**
	 * 扫描ReqKey注解
	 */
	public static void initReqKey() {
		Set<Class<?>> set = ClassUtil.scanPackageByAnnotation(AppSetting.app.getStr("app.scan"), ReqKey.class);
		List<String> objMethodOutList = Arrays.asList(AppSetting.app.getStr("app.method.object.out").split(","));
		for(Class<?> t : set){
			ReqKey rk = t.getAnnotation(ReqKey.class);
			String key = rk.value();//请求的key
			Method[] ms = t.getMethods();
			for(Method m : ms){
				if(!objMethodOutList.contains(m.getName())){
					String reqKey = key + "/" + m.getName();
					if(key.equals("/")){
						reqKey = reqKey.replace("//", "/");
					}
					IocFactory.reqKeyMap.put(reqKey, t.getName()+"#"+m.getName());
				}
			}
		}
		String str = IocFactory.reqKeyMap.toString();
		System.out.println("----------------------  Acat 注解加载ReqKey进行中 ----------------------");
	    str = str.replaceAll("\\{", " -  ");
	    str = str.replaceAll("\\}", "");
		str = str.replaceAll(",", "\r\n - ");
		System.out.println(str);
		System.out.println("----------------------  Acat 注解加载ReqKey完毕   ----------------------");
	}
}
